package com.leased.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.leased.core.ActionContext;
import com.leased.exception.DatabaseException;
import com.leased.exception.YCException;
import com.leased.pojo.CUsers;
import com.leased.pojo.OperateRecordInfo;
import com.leased.pojo.UserLoginLimit;
import com.leased.request.cuser.CUserAddRequest;
import com.leased.request.cuser.CUserListRequest;
import com.leased.request.operate.OperateRecordRequest;
import com.leased.response.CUserDetailResponse;
import com.leased.response.CUserResponse;
import com.leased.response.MyCarsResponse;
import com.leased.service.CUserService;
import com.leased.service.OperateRecordService;
import com.leased.service.UserLoginLimitService;
import com.leased.utils.DateTimeUtil;
import com.leased.utils.Page;
import com.leased.utils.Validator;
import com.leased.utils.YCSystemStatusEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static com.leased.handler.ZUserHandler.getNextDay;

/**
 * Created by shencx on 2017/8/1.
 */
@Service
public class CUserHandler {

    Logger LOG = LoggerFactory.getLogger(CUserHandler.class);

    @Resource
    private CUserService cUserService;

    @Resource
    private UserLoginLimitService userLoginLimitService;

    @Resource
    private OperateRecordService operateRecordService;

    /**
     * 添加修改车主信息
     * @param cUserAddRequest
     * @throws YCException
     */
    public void addCUserInfo(CUserAddRequest cUserAddRequest) throws YCException {
        /** 参数校验 */
        Validator.isEmpty(cUserAddRequest,YCSystemStatusEnum.PARAM_EMPTY);
        Validator.isEmpty(cUserAddRequest.getUserName(),"帐号不能为空");
        Validator.isEmpty(cUserAddRequest.getPassword(),"密码不能为空");
        CUsers cUsers = new CUsers();
        cUsers.setCuserId(cUserAddRequest.getCuserId());
        cUsers.setUsername(cUserAddRequest.getUserName());
        cUsers.setPassword(cUserAddRequest.getPassword());
        cUsers.setCertName(cUserAddRequest.getCertName());
        cUsers.setPhone(cUserAddRequest.getPhone());
        cUsers.setCarNumber(cUserAddRequest.getCarNumber());
        cUsers.setCarType(cUserAddRequest.getCarType());
        cUsers.setCarLength(cUserAddRequest.getCarLength());
        cUsers.setCarWeight(cUserAddRequest.getCarWeight());
        cUsers.setRunningRoute(cUserAddRequest.getRunningRoute());
        cUsers.setRunningRouteStart(cUserAddRequest.getRunningRouteStart());
        cUsers.setOperateName(ActionContext.getActionContext().currentUser().getName());
        cUsers.setBelongArea(cUserAddRequest.getBelongProvince()+"/"+cUserAddRequest.getBelongCity()+"/"+cUserAddRequest.getBelongCounty());
        cUsers.setType(0);

        try {
            if (cUserAddRequest.getCuserId() == null) {
                Integer id = cUserService.addCUserInfo(cUsers);
                if (id > 0){
                    //添加用户权限信息
                    JSONArray jsonArray = JSON.parseArray(cUserAddRequest.getExpireTime());
                    for (Object object : jsonArray) {
                        JSONObject jsonObject = JSONObject.parseObject(object.toString());
                        UserLoginLimit userLoginLimit = new UserLoginLimit();
                        userLoginLimit.setUserId(id);
                        userLoginLimit.setUserType(1);
                        userLoginLimit.setPlatformType(Integer.valueOf(jsonObject.get("platformType").toString()));
                        //到期时间有值则开通，没有则没
                        if (StringUtils.isNoneBlank(jsonObject.get("expire_time").toString())){
                            userLoginLimit.setBeUsed(1);
                            userLoginLimit.setExpireTime(DateTimeUtil.convertDate(jsonObject.get("expire_time").toString()));
                        }else {
                            userLoginLimit.setBeUsed(0);
                            userLoginLimit.setExpireTime(new Date());
                        }
                        userLoginLimitService.addUserLoginLimitInfo(userLoginLimit);
                    }
                }
            }else {
                boolean flag = cUserService.updateCUser(cUsers);
                //更新成功 插入操作记录
                if (flag){
                    OperateRecordInfo operateRecordInfo = new OperateRecordInfo();
                    operateRecordInfo.setUserType(1);
                    operateRecordInfo.setUserAccount(cUserAddRequest.getUserName());
                    operateRecordInfo.setOperateName(ActionContext.getActionContext().currentUser().getName());
                    operateRecordInfo.setOperateDescribe("修改了"+cUserAddRequest.getUserName()+"信息");
                    operateRecordService.addOperateRecordInfo(operateRecordInfo);
                }
            }
        } catch (DatabaseException e) {
            LOG.error("addCUserInfo exception",cUserAddRequest);
            throw new YCException(YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getCode(), YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getDesc());
        }

    }

    /**
     * 获取车主信息列表
     * @param cUserListRequest
     * @return
     * @throws YCException
     */
    public Page<CUserResponse> getCUserPage(CUserListRequest cUserListRequest) throws YCException {
        Page<CUserResponse> page = null;
        if (StringUtils.isNoneBlank(cUserListRequest.getUserName()) || StringUtils.isNoneBlank(cUserListRequest.getRealName()) || StringUtils.isNoneBlank(cUserListRequest.getPhoneNumber())
                || StringUtils.isNoneBlank(cUserListRequest.getStartTime()) || StringUtils.isNoneBlank(cUserListRequest.getEndTime())){

        }else {
            cUserListRequest.setStartTime(DateTimeUtil.formatDate(getNextDay(-1)));
            cUserListRequest.setEndTime(DateTimeUtil.formatDate(getNextDay(0)));
        }
        try {
            page = cUserService.fetchCUserInfoPage(cUserListRequest);
            return page;
        } catch (DatabaseException e) {
            LOG.error("getCUserPage exception",cUserListRequest);
            throw new YCException(YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getCode(), YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getDesc());
        }
    }

    /**
     * 获取车主用户详情
     * @param cUserListRequest
     * @return
     * @throws YCException
     */
    public CUsers getCUserDetail(CUserListRequest cUserListRequest) throws YCException {
        CUsers cUsers = null;
        try {
            cUsers = cUserService.fetchCUserDetail(cUserListRequest);
            return cUsers;
        } catch (DatabaseException e) {
            LOG.error("getCUserDetail exception",cUserListRequest);
            throw new YCException(YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getCode(), YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getDesc());
        }
    }

    /**
     * 查看车主用户明细
     * @param id
     * @return
     * @throws YCException
     */
    public CUserDetailResponse getCUserParticulars(Integer id) throws YCException {
        /** 参数校验 */
        Validator.isEmpty(id,"主键ID不能为空");
        CUserListRequest cUserListRequest = new CUserListRequest();
        cUserListRequest.setcUserId(id);
        try {
           CUsers cUsers = cUserService.fetchCUserDetail(cUserListRequest);
           CUserDetailResponse cUserDetailResponse = new CUserDetailResponse();
           if (cUsers != null){
               cUserDetailResponse.setUsername(cUsers.getUsername());
               cUserDetailResponse.setPassword(cUsers.getPassword());
               cUserDetailResponse.setPhone(cUsers.getPhone());
               cUserDetailResponse.setCertName(cUsers.getCertName());
               cUserDetailResponse.setCarNumber(cUsers.getCarNumber());
               cUserDetailResponse.setCarType(cUsers.getCarType());
               cUserDetailResponse.setCarLength(cUsers.getCarLength());
               cUserDetailResponse.setCarWeight(cUsers.getCarWeight());
               cUserDetailResponse.setRunningRoute(cUsers.getRunningRoute());
               cUserDetailResponse.setCarStatues(cUsers.getCarStatues());

               //获取权限列表
               List<UserLoginLimit> list = userLoginLimitService.fetchUserLoginLimitList(id,1);
               cUserDetailResponse.setLoginLimits(list);

               //获取操作记录列表
               OperateRecordRequest request = new OperateRecordRequest();
               request.setUserAccount(cUsers.getUsername());
               request.setUserType(1);
               List<OperateRecordInfo> recordInfoList = operateRecordService.fetchOperateRecordList(request);
               cUserDetailResponse.setRecordInfoList(recordInfoList);
           }
           return cUserDetailResponse;
        }catch (DatabaseException e) {
            LOG.error("getCUserParticulars exception",id);
            throw new YCException(YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getCode(), YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getDesc());
        }
    }

    /**
     * 获取我的车队列表
     * @param cUserListRequest
     * @return
     * @throws YCException
     */
    public Page<MyCarsResponse> getMyCarsList(CUserListRequest cUserListRequest) throws YCException {
        Page<MyCarsResponse> page = null;
        try {
            page = cUserService.fetchMyFleetPage(cUserListRequest);
            return page;
        }catch (DatabaseException e) {
            LOG.error("getMyCarsList exception",cUserListRequest);
            throw new YCException(YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getCode(), YCSystemStatusEnum.INVOKE_API_RETURN_EXCEPTION.getDesc());
        }
    }
}
